package online.heycm.platform.common.entity.result;

import java.io.Serializable;

import online.heycm.platform.common.entity.exception.Assert;
import online.heycm.platform.common.tools.Jackson;
import org.apache.commons.lang3.StringUtils;

/**
 * 统一返回对象
 *
 * @author heycm
 * @since 2022年6月1日 20点57分
 */
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 响应码：默认成功-200 默认失败-500
     */
    private int code;

    /**
     * 响应说明
     */
    private String message;

    /**
     * 响应数据
     */
    private T data;

    private Result() {}

    public static <T> Result<T> success() {
        return new Result<T>().code(200).message("成功");
    }

    public static <T> Result<T> success(T data) {
        return new Result<T>().code(200).data(data).message("成功");
    }

    public static <T> Result<T> success(int code, T data) {
        return new Result<T>().code(code).data(data).message("成功");
    }

    public static <T> Result<T> error() {
        return new Result<T>().code(500).message("失败");
    }

    public static <T> Result<T> error(String message) {
        return new Result<T>().code(500).message(message);
    }

    public static <T> Result<T> error(int code, String message) {
        return new Result<T>().code(code).message(message);
    }

    public static <T> Result<T> error(ErrorCode errorCode) {
        return error(errorCode.code(), errorCode.message());
    }

    public static <T> Result<T> optional(Optional<T> optional) {
        return optional.fail() ? error(optional.error()) : success(optional.get());
    }

    public static <T> T extData(Result<T> result) {
        Assert.require(result);
        return result.getData();
    }

    public boolean ok() {
        return code == 200;
    }

    private Result<T> code(int code) {
        this.code = code;
        return this;
    }

    private Result<T> message(String message) {
        this.message = message;
        return this;
    }

    private Result<T> data(T data) {
        this.data = data;
        return this;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }

    @Override
    public String toString() {
        return toJson();
    }

    public String toJson() {
        return Jackson.toJson(this);
    }

    public String toJsonWithoutData() {
        return new StringBuilder()
                .append("{")
                .append("\"code\": ").append(code).append(", ")
                .append("\"message\": \"").append(StringUtils.isEmpty(message) ? "\"\"" : message).append("\"")
                .append("}")
                .toString();
    }
}
